package com.ok.common.utils

import android.content.Context
import android.content.SharedPreferences
import com.ok.common.base.AppContext
import com.ok.common.ext.jsonToObject
import com.ok.common.ext.toJson
import com.squareup.moshi.Moshi

object SpUtils {

    val sp: SharedPreferences by lazy {
        AppContext.getSharedPreferences("default", Context.MODE_PRIVATE)
    }

    fun set(key: String, value: Any?) = with(sp.edit()) {
        when (value) {
            is Long -> putLong(key, value)
            is String -> putString(key, value)
            is Int -> putInt(key, value)
            is Boolean -> putBoolean(key, value)
            is Float -> putFloat(key, value)
            else -> putString(key, value?.toJson())
        }.apply()
    }

    /**
     * 内联函数使用的方法和属性的权限修饰符必须是public
     * */
    inline fun <reified T> get(key: String, default: T): T {
        if (!sp.contains(key)) return default
        return with(sp) {
            when (default) {
                is Int -> getInt(key, default) as T
                is Long -> getLong(key, default) as T
                is Float -> getFloat(key, default) as T
                is Boolean -> getBoolean(key, default) as T
                is String -> getString(key, default) as T
                else -> getString(key, "")!!.jsonToObject<T>() ?: default
            }
        }
    }

    fun remove(key: String): Boolean {
        if (!sp.contains(key)) return true
        sp.edit().remove(key).apply()
        return true
    }

    fun clear() {
        sp.edit().clear().apply()
    }

}

